package com.kkb.controller;


import com.kkb.domain.AjaxResult;
import com.kkb.service.QiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;

import static com.kkb.domain.AjaxResult.error;
import static com.kkb.domain.AjaxResult.success;

@Controller
@RequestMapping("/imgUpload")
public class UploadImageController {
    @Autowired
    private QiniuService qiniuService;

    @RequestMapping(value = "/testUpload", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        System.out.println("开始图片上传");
        if(file.isEmpty()){
            AjaxResult.error();
        }
        String url = qiniuService.saveImage(file);
        if(url==null){
            return AjaxResult.error("上传图片异常，请稍后再试！！！");
        }
        return AjaxResult.success(url);

    }

    /**
     * 图片批量上传
     * @param files
     * @param request
     * @return
     */
    @RequestMapping(value = "/batchUpload", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult batchUploadImg(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        System.out.println("开始图片上传");
        ArrayList<String> arrayList = new ArrayList<>();
        //有的规格可以不用传，所以不用判断是否为空
        if(files.length>0){
            for (MultipartFile file : files) {
                String url = qiniuService.saveImage(file);
                if(url==null){
                    return AjaxResult.error("上传图片异常，请稍后再试！！！");
                }else{
                    arrayList.add(url);
                }
            }
        }

        return AjaxResult.success(arrayList);

    }

}
